package com.cyan.app.workflow.activity.Wap;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;

import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.AppContext;
import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.CommonBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by DXW on 2016-05-25.
 */
public class WebViewActivity extends BaseActivity  {
    public static final String TAG = "MannoInfoActivity";
    private TextView mTextViewManno;
    private Button mButton;
    private String barcode ;
    private WebView mWebView1;
    private  String weburl="";
    private  String filename ="";
    private ShowTipDialog showdialog = new ShowTipDialog();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webpage);
        initView();
        mWebView1 = (WebView) findViewById(R.id.web);
        mWebView1.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                // 监听下载功能，当用户点击下载链接的时候，直接调用系统的浏览器来下载
                /*Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);*/
                filename =url.substring(url.lastIndexOf("/")+1);
                downFile(url);
            }
        });
        mWebView1.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                 setProgress(newProgress*100);
            }
        });
        mWebView1.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
               /* Uri uri = Uri.parse(url);
                Intent viewIntent = new Intent(Intent.ACTION_VIEW,uri);
                startActivity(viewIntent);*/
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                String dataString = AppUtils.getFromAssets(AppContext.getInstance(), "404.html");
                view.loadDataWithBaseURL("404.html", dataString, "text/html", "UTF-8", "");
            }
        });
        mWebView1.getSettings().setJavaScriptEnabled(true);
        mWebView1.getSettings().setDomStorageEnabled(true);
        mWebView1.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

        mWebView1.getSettings().setSupportZoom(true);
        mWebView1.getSettings().setBuiltInZoomControls(true);

        mWebView1.getSettings().setUseWideViewPort(true);
        mWebView1.getSettings().setLoadWithOverviewMode(true);

        if (android.os.Build.VERSION.SDK_INT > 10) {
            mWebView1.getSettings().setDisplayZoomControls(false);
        }
       // mWebView1.loadUrl("http://www.sina.com.cn");
//        AsyncLoader task1 = new AsyncLoader();
//        task1.execute("GetUrl", "QueryBarcode", "1232'");
        barcode = getIntent().getStringExtra("sm_content");

        if(barcode!=null&&!barcode.isEmpty()) {
            if(barcode.indexOf("100")==0||barcode.indexOf("300")==0||barcode.indexOf("200")==0||barcode.indexOf("400")==0) {
                mTextViewManno.setText(barcode.substring(5));
            }else {
                mTextViewManno.setText(barcode);
            }
            AsyncLoader task = new AsyncLoader();
            task.execute("GetUrl", "QueryBarcode", barcode);
        }else{
           startActivityForResult(new Intent(WebViewActivity.this, CaptureActivity.class), 0x0002);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView1.canGoBack()) {
            mWebView1.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x0002 && resultCode == RESULT_OK) {
            String result = "";
            if (data != null) {
                result = data.getStringExtra("result");
            }
            if(result.indexOf("100")==0||result.indexOf("300")==0||result.indexOf("200")==0||result.indexOf("400")==0) {
                mTextViewManno.setText(String.valueOf(result.substring(5)));
            }else {
                mTextViewManno.setText(result);
            }
            barcode = String.valueOf(result);
            AsyncLoader task = new AsyncLoader();
            task.execute("GetUrl", "QueryBarcode", barcode);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void initView(){
        titleBar();
        mTextViewManno = (TextView) findViewById(R.id.top_search);
        mTextViewManno.setInputType(InputType.TYPE_NULL);
        mTextViewManno.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(WebViewActivity.this, CaptureActivity.class), 0x0002);
            }
        });
    }

    private void titleBar() {
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                //WebViewActivity.this.setResult(RESULT_OK);
                finish();
            }
        });
        mButton = (Button)findViewById(R.id.top_title_refres_with_icon);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(WebViewActivity.this, CaptureActivity.class), 0x0002);
            }
        });
    }
    public class AsyncLoader extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            showdialog.showDialog(WebViewActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try{
                JSONObject param = new JSONObject();
                param.put("Type", params[1]);
                param.put("Code", params[2]);
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, params[0], param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null||s.isEmpty()) {
                showdialog.closeDialog();
                return;
            }
            CommonBean commonBean = new Gson().fromJson(s, CommonBean.class);
            if (commonBean.getCode() < 0) {
                AppUtils.showTip(WebViewActivity.this, commonBean.getMsg());
            } else {
                weburl = commonBean.getResult();
                weburl = HttpConfig.HTTP_MAIN_BASE_URL+weburl+ "&UserNo=" + AppData.getInstance().getUserId()  + "&ConnectString=" + AppData.getInstance().getConnectstring() + "&FactoryID=" + HttpConfig.Main_FactoryID;
                Log.e("error", weburl);
                mWebView1.loadUrl(weburl);
            }
            showdialog.closeDialog();
        }
    }
    void downFile(final String url) {
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(Environment.getExternalStorageDirectory(),
                                filename);
                        fileOutputStream = new FileOutputStream(file);

                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    down();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }.start();
    }
    private Handler handler = new Handler();
    void down() {
        handler.post(new Runnable() {
            public void run() {
                update();
            }
        });
    }
    // 下载后打开
    void update() {


        Intent intent = new Intent(Intent.ACTION_VIEW);
        /*if(filename.contains(".dwg")) {
            intent.setDataAndType(
                    Uri.fromFile(new File(Environment.getExternalStorageDirectory(), filename)),
                    "application/x-autocad");
        }else if(filename.contains(".xls")) {
            intent.setDataAndType(
                    Uri.fromFile(new File(Environment.getExternalStorageDirectory(), filename)),
                    "application/vnd.ms-excel");
        }else if(filename.contains(".xls")) {
            intent.setDataAndType(
                    Uri.fromFile(new File(Environment.getExternalStorageDirectory(), filename)),
                    "application/vnd.ms-excel");
        }else {
            return;
        }*/
        String type = getMIMEType(filename);
        intent.setDataAndType(
                Uri.fromFile(new File(Environment.getExternalStorageDirectory(), filename)),
                type);
        WebViewActivity.this.startActivity(intent);
        //((Activity)WebViewActivity.this).finish();
    }

    private String getMIMEType(String fileName) {
        String[][] MIME_MapTable={
                //{后缀名，MIME类型}
                {".3gp",    "video/3gpp"},
                {".apk",    "application/vnd.android.package-archive"},
                {".asf",    "video/x-ms-asf"},
                {".avi",    "video/x-msvideo"},
                {".bin",    "application/octet-stream"},
                {".bmp",    "image/bmp"},
                {".c",  "text/plain"},
                {".class",  "application/octet-stream"},
                {".conf",   "text/plain"},
                {".cpp",    "text/plain"},
                {".doc",    "application/msword"},
                {".docx",   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
                {".xls",    "application/vnd.ms-excel"},
                {".xlsx",   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
                {".exe",    "application/octet-stream"},
                {".gif",    "image/gif"},
                {".gtar",   "application/x-gtar"},
                {".gz", "application/x-gzip"},
                {".h",  "text/plain"},
                {".htm",    "text/html"},
                {".html",   "text/html"},
                {".jar",    "application/java-archive"},
                {".java",   "text/plain"},
                {".jpeg",   "image/jpeg"},
                {".jpg",    "image/jpeg"},
                {".js", "application/x-javascript"},
                {".log",    "text/plain"},
                {".m3u",    "audio/x-mpegurl"},
                {".m4a",    "audio/mp4a-latm"},
                {".m4b",    "audio/mp4a-latm"},
                {".m4p",    "audio/mp4a-latm"},
                {".m4u",    "video/vnd.mpegurl"},
                {".m4v",    "video/x-m4v"},
                {".mov",    "video/quicktime"},
                {".mp2",    "audio/x-mpeg"},
                {".mp3",    "audio/x-mpeg"},
                {".mp4",    "video/mp4"},
                {".mpc",    "application/vnd.mpohun.certificate"},
                {".mpe",    "video/mpeg"},
                {".mpeg",   "video/mpeg"},
                {".mpg",    "video/mpeg"},
                {".mpg4",   "video/mp4"},
                {".mpga",   "audio/mpeg"},
                {".msg",    "application/vnd.ms-outlook"},
                {".ogg",    "audio/ogg"},
                {".pdf",    "application/pdf"},
                {".png",    "image/png"},
                {".pps",    "application/vnd.ms-powerpoint"},
                {".ppt",    "application/vnd.ms-powerpoint"},
                {".pptx",   "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
                {".prop",   "text/plain"},
                {".rc", "text/plain"},
                {".rmvb",   "audio/x-pn-realaudio"},
                {".rtf",    "application/rtf"},
                {".sh", "text/plain"},
                {".tar",    "application/x-tar"},
                {".tgz",    "application/x-compressed"},
                {".txt",    "text/plain"},
                {".wav",    "audio/x-wav"},
                {".wma",    "audio/x-ms-wma"},
                {".wmv",    "audio/x-ms-wmv"},
                {".wps",    "application/vnd.ms-works"},
                {".xml",    "text/plain"},
                {".dwg",    "application/autocad"},
                {".z",  "application/x-compress"},
                {".zip",    "application/x-zip-compressed"},
                {"",        "*/*"}
        };

        String type="*/*";
        //获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fileName.lastIndexOf(".");
        if(dotIndex < 0){
            return type;
        }
    /* 获取文件的后缀名*/
        String end=fileName.substring(dotIndex,fileName.length()).toLowerCase();
        if(end=="")return type;
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for(int i=0;i<MIME_MapTable.length;i++){
            if(end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

}
